const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    doctorName: '',
    user: '',
    selectDoctor: '',
    showTime: false, //时间弹窗
    showSheet: false, //选择器弹窗
    currentDate: new Date().getTime(),
    minDate: new Date('1900-02-01').getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
    selectStr: '', //选择弹窗绑定的属性
    actions: [],
    userPhoto: '',
    fileList: [],
    doctorList: [], //医生列表
    doctors: []
  },



  // 上传头像
  upHandle() {
    var that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      camera: 'back',
      success(res) {
        console.log(res.tempFiles)
        that.setData({
          userPhoto: res.tempFiles[0],
          fileList: res.tempFiles,
        })
        console.log(that.data.userPhoto);
      }
    })
  },



  // 保存
  saveHandle() {
    var user = this.data.user;
    if (user.userImg == null && this.data.userPhoto == '') {
      wx.showToast({
        title: '请上传头像',
        icon: 'none'
      })
      return
    } else if (user.userName == '') {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    } else if (user.userTel == '') {
      wx.showToast({
        title: '请输入电话',
        icon: 'none'
      })
      return
    } else if (user.cardCode == '') {
      wx.showToast({
        title: '请输入身份证号码',
        icon: 'none'
      })
      return
    } else if (user.userSex == '') {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      })
      return
    } else if (user.birth == '') {
      wx.showToast({
        title: '请选择出生日期',
        icon: 'none'
      })
      return
    } else if (user.doctorId == 0) {
      wx.showToast({
        title: '请选择您的医生',
        icon: 'none'
      })
      return
    }
    var url = app.globalData.url + "user/updateUser",
      that = this;
    wx.showLoading({
      title: '',
    })
    console.log(that.data.fileList);
    console.log(user);
    // return
    if (this.data.userPhoto != '') {
      // if (true) {
      wx.uploadFile({
        filePath: that.data.fileList[0].tempFilePath,
        name: 'file',
        url: url,
        formData: {
          userId: app.globalData.userId,
          doctorId: user.doctorId,
          userCode: user.cardCode,
          userName: user.userName,
          birth: user.birth,
          tel: user.userTel,
          sex: user.userSex,
          familyId: user.familyId == null ? 0 : user.familyId,
          userType: user.userType,
        },
        success(res) {
          var res = JSON.parse(res.data)
          console.log(res);
          user.age = that.jsGetAge(user.birth)
          user.userImg = res.data.userImg
          app.globalData.user = user
          app.globalData.doctor = that.data.selectDoctor
          console.log(app.globalData);
          wx.setStorageSync('user', JSON.stringify(user))
          wx.setStorageSync('doctor', JSON.stringify(that.data.selectDoctor))
          if (res.flag) {
            wx.hideLoading()
            wx.showModal({
              title: '提示',
              content: '信息保存成功',
              showCancel: false,
              complete: (res) => {
                if (res.confirm) {
                  wx.switchTab({
                    url: '/pages/index/index',
                  })
                }
              }
            })
          }
        }
      })
    } else {
      app.wxRequest(url, {
          userId: app.globalData.userId,
          doctorId: user.doctorId,
          userCode: user.cardCode,
          userName: user.userName,
          birth: user.birth,
          tel: user.userTel,
          sex: user.userSex,
          familyId: user.familyId == null ? 0 : user.familyId,
          userType: user.userType,
        }, res => {
          console.log(res);
          if (res.flag) {
            wx.hideLoading()
            console.log(user);
            if (res.data.userImg != null) {
              user.userImg = res.data.userImg
            }
            user.age = that.jsGetAge(user.birth)
            app.globalData.user = user
            app.globalData.doctor = that.data.selectDoctor
            wx.setStorageSync('user', JSON.stringify(user))
            wx.setStorageSync('doctor', JSON.stringify(that.data.selectDoctor))
            console.log(app.globalData.user);
            wx.showModal({
              title: '提示',
              content: '提交成功',
              showCancel: false,
              complete: (res) => {
                if (res.confirm) {
                  wx.navigateBack()

                }
              }
            })
            console.log(that.data);
          }
        },
        err => {
          console.log(err);
        })
    }
    console.log(user);
  },

  jsGetAge(strBirthday) {
    var returnAge;
    var strBirthdayArr = strBirthday.split("-");
    var birthYear = strBirthdayArr[0];
    var birthMonth = strBirthdayArr[1];
    var birthDay = strBirthdayArr[2];

    var d = new Date();
    var nowYear = d.getFullYear();
    var nowMonth = d.getMonth() + 1;
    var nowDay = d.getDate();

    if (nowYear == birthYear) {
      returnAge = 0; //同年 则为0岁
    } else {
      var ageDiff = nowYear - birthYear; //年之差
      if (ageDiff > 0) {
        if (nowMonth == birthMonth) {
          var dayDiff = nowDay - birthDay; //日之差
          if (dayDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        } else {
          var monthDiff = nowMonth - birthMonth; //月之差
          if (monthDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        }
      } else {
        returnAge = -1;
      }
    }

    return returnAge;

  },

  // 输入框编辑
  inputHandle(e) {
    var str = e.currentTarget.dataset.flag
    var val = e.detail.value
    this.setData({
      [str]: val
    })
  },

  // 选择出生日期
  showTimeHandle() {
    this.setData({
      showTime: true
    })
  },
  // 关闭时间选择
  onClose() {
    this.setData({
      showTime: false
    })
  },

  // 确认日期
  confirmTime(event) {
    console.log(event);
    var date = new Date(event.detail)
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
    var strDate = Y + M + D;
    console.log(strDate);
    var str = 'user.birth'
    this.setData({
      [str]: strDate,
      showTime: false
    });
  },
  // 选择框
  onChange(event) {
    var str = event.currentTarget.dataset.flag
    this.setData({
      [str]: event.detail
    });
    console.log(this.data.userHealth);
  },
  // 显示选择弹窗
  showSelect(e) {
    console.log(e);
    var str = e.currentTarget.dataset.flag;

    this.setData({
      actions: this.data.doctorList,
      selectStr: str,
      showSheet: true
    })

  },

  // 选择弹窗  确认
  onSelect(e) {
    var doctors = this.data.doctors,
      selectDoctor = '';
    console.log(e);

    doctors.forEach(ele => {
      if (ele.doctorId = e.detail.id) {
        selectDoctor = ele
      }
    })
    this.setData({
      [this.data.selectStr]: e.detail.id,
      doctorName: e.detail.name,
      showSheet: false,
      selectDoctor
    })
    console.log(this.data);
  },




  getDoctorList() {
    var url = app.globalData.url + "doctor/listDoctors",
      doctorList = [],
      user = this.data.user,
      doctorName = '',
      that = this;
    wx.showLoading({
      title: '',
    })
    app.wxRequest(url, {}, res => {
        console.log(res);
        if (res.flag) {
          wx.hideLoading()
          console.log(user);
          console.log(user);
          res.data.forEach(ele => {
            if (ele.doctorId == user.doctorId) {
              doctorName = ele.doctorName
            }

            doctorList.push({
              name: ele.doctorName,
              id: ele.doctorId,
            })
          })
          that.setData({
            doctorList,
            doctorName,
            doctors: res.data
          })
          console.log(that.data);
        }
      },
      err => {
        console.log(err);
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    var user = app.globalData.user;
    if (app.globalData.myDoctorId != 0) {
      user.doctorId = app.globalData.myDoctorId
    }
    console.log(user);
    this.setData({
      user
    })
    this.getDoctorList()
    console.log(this.data);

    console.log(app.globalData.user);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})